package com.alix.paymoney.utils;

import android.os.Handler;
import android.os.Message;

/**
 * Created by wushiqian on 2017/11/13.
 */

public class TimerManger {
    private long time;
    private long startTime;
    private OnCountDownListener onCountDownListener;

    public void setOnCountDownListener(OnCountDownListener onCountDownListener) {
        this.onCountDownListener = onCountDownListener;
    }

    public TimerManger(long time) {
        this.time = time;
    }

    public void start() {
        isRunning=true;
        startTime = System.currentTimeMillis();
        handler.sendEmptyMessage(1);
    }

    public interface OnCountDownListener {
        void onTick(long left);

        void onFinish();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (isRunning){
                        long left = time + startTime - System.currentTimeMillis();
                        if (left > 0) {
                            sendEmptyMessage(1);
                            if (onCountDownListener != null) {
                                onCountDownListener.onTick(left);
                            }

                        } else {
                            if (onCountDownListener != null) {
                                onCountDownListener.onFinish();
                            }
                            isRunning=false;
                        }
                    }

                    break;
            }
        }
    };
    boolean isRunning;
    public boolean isRunning(){
        return isRunning;
    }
    public void cancel() {
        isRunning=false;
        handler.removeMessages(1);
    }
}
